package com.jiawei.server;

import com.jiawei.message.decode.StringProtocol;
import org.smartboot.socket.MessageProcessor;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.transport.AioQuickServer;
import org.smartboot.socket.transport.AioSession;

import java.io.IOException;

/**
 * @author : willian fu
 * @version : 1.0
 */
public class TcpServer {
    private Integer port;

    public TcpServer(Integer port) {
        this.port = port;
    }

    public void run() throws IOException {
        // 1
        AioQuickServer<String> server = new AioQuickServer<String>(port, new StringProtocol(), new MessageProcessor<String>() {
            @Override
            public void process(AioSession<String> session, String msg) {
                System.out.println("接受到客户端消息:" + msg);

                byte[] response = "Hi Client!".getBytes();
                byte[] head = {(byte) response.length};
                try {
                    session.writeBuffer().write(head);
                    session.writeBuffer().write(response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void stateEvent(AioSession<String> session,
                                   StateMachineEnum stateMachineEnum,
                                   Throwable throwable) {
                switch (stateMachineEnum){
                    //客户端连接上来
                    case NEW_SESSION:
                        try {
                            System.out.println("与客户端连接建立"+session.getRemoteAddress());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    //服务端拒绝客户端连接请求
                    case REJECT_ACCEPT:break;
                    //数据读取完毕时触发
                    case INPUT_SHUTDOWN:break;
                    //AioSesson完成close操作后触发
                    case SESSION_CLOSED:break;
                    //解码异常
                    case DECODE_EXCEPTION:break;
                    //读数据过程中发生异常时触发
                    case INPUT_EXCEPTION:break;
                    //触发了AioSession.close方法，但由于当前AioSession还有未完成的事件，会进入SESSION_CLOSING状态
                    case SESSION_CLOSING:break;
                    //写数据过程中发生异常时触发
                    case OUTPUT_EXCEPTION:break;
                    //业务处理异常
                    case PROCESS_EXCEPTION:break;
                    default:break;
                }
            }
        });
        //2
        server.start();
    }

}
